#include <bpf_common.h>
#include <stdio.h>
#include <string.h>
#include <uthash.h>
#include <kprobe_test.h>
#include <procstat.h>

#define MAX_MODULES_NAME_LEN 64

typedef struct {
	char name[MAX_MODULES_NAME_LEN];
	bpf_module* module;
	UT_hash_handle hh; /* makes this structure hashable */
} module_hash;

module_hash* modules_list = NULL;

int register_module(bpf_module* module) {
	module_hash* bpf = NULL;

	HASH_FIND_STR(modules_list, module->name, bpf);
	if (bpf) {
		printf("Module is exists\n");
		return -1;
	}

	bpf = (module_hash*)calloc(1, sizeof(*bpf));
	if (!bpf) {
		printf("Memory alloc fail\n");
		return -1;
	}
	strncpy(bpf->name, module->name, MAX_MODULES_NAME_LEN);
	bpf->module = module;
	HASH_ADD_STR(modules_list, name, bpf);

	return 0;
}

bpf_module* find_module(char* name) {
	module_hash* bpf = NULL;

	HASH_FIND_STR(modules_list, name, bpf);
	if (!bpf) {
		printf("Module not found\n");
		return NULL;
	}
	return bpf->module;
}

bpf_module kprobe_test_module = {
	.name = "kprobe_test",
	.open = kprobe_test_open,
	.run = kprobe_test_run,
	.release = kprobe_test_release,
};

bpf_module procstat_module = {
	.name = "procstat",
	.open = procstat_open,
	.run = procstat_run,
	.release = procstat_release,
};

void bpf_common_init() {
	register_module(&kprobe_test_module);
	register_module(&procstat_module);
}
